//导入express
const express = require("express")
//引入数据库对象
const connection = require(`${__dirname}/../mysql/index.js`)
//创建路由对象
const router = express.Router()

//添加小部件
/*参数
* image String 必传 展示图片路径
* path String 必传 模型路径
* model String 必传 模型文件名*/
router.get("/add_widget",(req, res)=>{
    const {image,path,model} = req.query
    if(
        image === undefined || image === "" ||
        path === undefined || path === "" ||
        model === undefined || model === ""
    ){
        return res.send({code: 1,data: {},msg: "必传参数缺失"})
    }
    const sql = `insert into widget(w_img,w_path,w_model)
                values("${image}","${path}","${model}")`
    connection.query(sql,(err,result)=>{
        if(err){
            console.log(err)
            res.send({code: 1,data: {},msg: "添加失败"})
        }else{
            res.send({code: 0,data: {wid: result.insertId},msg: "添加成功"})
        }
    })
})

//查询小部件
/*参数
* wid int 可选 小部件id
* 若无参数则查询所有小部件信息*/
router.get("/get_widget",(req,res)=>{
    const {wid} = req.query
    const sql = `select * from widget where 1 = 1 ${wid ? `and w_id = ${wid}` : ""}`
    connection.query(sql,(err,result)=>{
        if(err){
            res.send({code: 1,data: {},msg: "查询失败"})
        }else{
            const widgetList = []
            result.map(item=>{
                const data = {
                    wid: item.w_id,
                    image: item.w_img,
                    path: item.w_path,
                    model: item.w_model
                }
                widgetList.push(data)
            })
            res.send({code: 0,data: {widgetList},msg: "查询成功"})
        }
    })
})

//操作小部件
/*参数
* type String 必传 操作类型，delete——删除，update——修改
* wid int 必传 小部件id
* image String 可选 展示图片
* path String 可选 模型路径
* model String 可选 模型文件名*/
router.get("/update_widget",(req,res)=>{
    const {type,wid,image,path,model} = req.query
    if(type === undefined || type === "" || wid === undefined || wid === ""){
        return res.send({code: 1,data: {},msg: "必传参数缺失"})
    }
    let sql
    let msg
    if(type === "delete"){
        msg = "删除"
        sql = `delete from widget where w_id = ${wid}`
    }else if(type === "update"){
        msg = "修改"
        sql = `update widget set w_id = ${wid}
                ${image ? `,w_img = "${image}"` : ""} 
                ${path ? `,w_path = "${path}"` : ""} 
                ${model ? `,w_model = "${model}"` : ""} 
                where w_id = ${wid}`
    }else{
        return res.send({code: 1,data: {},msg: "请选择正确的 'type' 值"})
    }
    connection.query(sql,(err)=>{
        if(err){
            res.send({code: 1,data: {},msg: `${msg}失败`})
        }else{
            res.send({code: 0,data: {},msg: `${msg}成功`})
        }
    })
})

module.exports = router

